package com.ruoyi.framework.file;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ruoyi.common.enums.FileExceptionEnum;
import com.ruoyi.common.enums.FileLocationEnum;
import com.ruoyi.common.enums.FileStatusEnum;
import com.ruoyi.common.exception.file.FileException;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.SysFileEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;

public class FileInfoFactory {
    public static SysFileEntity createSysFileInfo(MultipartFile file, String fileBucket, char secretFlag) {
        Long fileId = IdWorker.getId();
        String originalFilename = file.getOriginalFilename();
        String fileSuffix = null;
        if (ObjectUtil.isNotEmpty(originalFilename)) {
            fileSuffix = StrUtil.subAfter(originalFilename, ".", true);
        }
        SysFileEntity sysFileInfo = new SysFileEntity();
        try {
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(fileBucket, file);
            long fileSizeKb = Convert.toLong(NumberUtil.div(new BigDecimal(file.getSize()), BigDecimal.valueOf(1024L)).setScale(0, 4));
            String fileSizeInfo = FileUtil.readableFileSize(file.getSize());
            sysFileInfo.setFileCode(fileId);
            sysFileInfo.setFileLocation(FileLocationEnum.LOCAL.getCode());
            sysFileInfo.setFileBucket(fileBucket);
            sysFileInfo.setFileOriginName(fileName);
            sysFileInfo.setFileSuffix(fileSuffix);
            sysFileInfo.setFileSizeKb(fileSizeKb);
            sysFileInfo.setFileSizeInfo(fileSizeInfo);
            sysFileInfo.setFileStatus(FileStatusEnum.NEW.getCode());
            sysFileInfo.setSecretFlag(secretFlag);
            sysFileInfo.setDelFlag('N');
        } catch (IOException var13) {
            throw new FileException(FileExceptionEnum.ERROR_FILE.getErrorCode(), new Object[]{var13.getMessage()});
        }
        return sysFileInfo;
    }
}